﻿// Initialize app
var myApp = new Framework7({
    //template7Pages: true, //enable Template7 rendering for pages
    //Specify templates/pages data
    precompileTemplates: true,
    template7Pages: true,
});
// If we need to use custom DOM library, let's save it to $$ variable:
var $$ = Framework7.$;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we want to use dynamic navbar, we need to enable it for this view:
    dynamicNavbar: true,
})

var currentPage = 1;
var alreadyAlert = true;

var contextSearchText;

var menuController = {
    indexDefaultToolbar:function(){
        //主页默认菜单栏样式
        var toolbarHtml = '<div class="toolbar-inner" style="background-color:white;">' +
            '<a class="button" id="toolbar-button" onclick="handler()" style="width:60%;margin-left: 20%;background-color:#509AF1;color:white;height:40px;line-height:40px;border-radius:2px;">搜索</a>' +
            '</div>';
        $("#index-tool").html(toolbarHtml);
        mainView.showToolbar();
    },
    indexDefaultNavbar:function(){
        var navbarToolHtml = '<div class="left">' +
            '       <a class="link left" onClick="targetPage()" id="back"><i class="icon icon-back"></i><span>返回</span></a>' +
            '   </div>' +
            '   <div class="center sliding">门票折券</div>' +
            '   <a class="link right" onClick="showSearchPage()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;搜索</a>' +
            '</div>';
        $(".navbar-inner").html(navbarToolHtml);
    },
    indexNoneSearchNavbar:function(){
        var navbarToolHtml = '<div class="left">' +
            '       <a class="link" onClick="targetPage()" id="back"><i class="icon icon-back"></i><span>返回</span></a>' +
            '   </div>' +
            '   <div class="center sliding">门票折券</div>' +
            '   <div class="right" id="sellerShop">' +
            '</div>';
        $(".navbar-inner").html(navbarToolHtml);
    },
    keyWordSearchTagPage: function () {
        navbarShow();
        navbarStyle();
        //取得搜索类型
        $("#typeId a").on("click", function () {
            $("#typeIdInput").val($(this).attr("data-value"));
            searchPara.typeId = $(this).text().trim();
            $("#typeIdValue").html(searchPara.typeId);
        });

        $(".hot_search button").on("click", function () {
            searchPara.searchKeyWord = $(this).text();
            $("#tool_input_searchKeyWord").val(searchPara.searchKeyWord);
            handler();
        });

        function navbarShow() {
            var html = ' <div style="width:12%;float:left;text-align: center;"><a class="link" onClick="targetPage()" id="back">返回</a></div>' +
                '    <div style="width:60%;float:left"><input id="tool_input_searchKeyWord" type="text" placeholder="请输入关键字" style="width:100%;height:35px;border-radius: 38px;webkit-border-radius:38px;' +
                'moz-border-radius :38px;' +
                'background-color: #E8E8E8;' +
                'border: solid 0px #000;appearance:none;-moz-appearance:none;-webkit-appearance:none;' +
                'font-size: 20px;padding:0 20px;' +
                '"/></div>' +
                '<div style="width:18%;float:left;text-align: center">' +
                '<div class="btn-group" role="group" id="typeId">' +
                '<button type="button" class="btn btn-default dropdown-toggle" style="border:1px solid #4a90e2;color:#4a90e2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' +
                '<span id="typeIdValue">全部</span>' +
                '   <span class="caret"></span>' +
                '   </button>' +
                '   <ul class="dropdown-menu">' +
                '   <li><a href="#" data-value="">全部</a></li>' +
                '   <li><a href="#" data-value="1">门票</a></li>' +
                '   <li><a href="#" data-value="2">购物</a></li>' +
                '   <li><a href="#" data-value="3">餐饮</a></li>' +
                '   </ul>' +
                '   </div>' +
                '</div>';
            $(".navbar-inner").html(html);
            $("#tool_input_searchKeyWord").on("change", function () {
                var v = $(this).val();
                searchPara.searchKeyWord = v;
                $("#searchTag-content").val(v);
            })
            $("#tool_input_searchKeyWord").val(searchPara.searchKeyWord);
        }

        function navbarStyle() {
            $(".navbar-inner").css("background", "#FFFFFF");
            $(".page .page-content").css("background", "#f0f0f0");
            $(" .navbar a.link, .subnavbar a.link, .toolbar a.link ").css("display", "block");
        }

    },
    keyWordSearchPage:function(){

    },
    indexPage: function () {
        App.cityInputCenter();
        $("table tr td img").on("click", function () {
            var src = $(this).attr("src");
            if (src.indexOf("true") != -1) {
                ///$(this).attr("src",src.replace("true","false"));
            } else {
                var label = $("table tr td img");
                for (var tt = 0; tt < label.length; tt++) {
                    var ttSrc = $(label[tt]).attr("src");
                    if (ttSrc.indexOf("true") != -1) {
                        $(label[tt]).attr("src", ttSrc.replace("true", "false"));
                    }
                }
                $(this).attr("src", src.replace("false", "true"));
                var test = $(this).parent().next();
                var tt = 2;
                while (test.html()) {
                    tt--;
                    test = test.next();
                }
                $("#img-font td").removeClass("selected-img");
                $("#img-font td:eq(" + tt + ")").addClass("selected-img");
            }
        });
    }
}
var searchPara = {
    PageSize: 10, //分页参数， 页大小，默认为10
    PageNumber: 1, //分页参数，页码，默认为1
    searchKeyWord: '',//搜索关键字，默认为空
    typeId: '', //类型主键默认为0，搜索全部
    cityId: '',//城市主键默认为0，搜索全部

}
var staticPara={
    pageTag:false
}

$$(document).on('pageAfterAnimation', function (e) {
    var pageName = e.detail.page.name;
    if (pageName === 'contentSearchTagPage') {
        menuController.keyWordSearchTagPage();
        menuController.indexDefaultToolbar();
        mainView.showToolbar();
        loadSearchHistory();
    } else if (pageName === 'index') {
        menuController.indexDefaultToolbar();
    } else if (pageName === 'search') {
        mainView.hideToolbar();
        App.hideSellerShop();
    }else if(pageName === 'keyWordSearchPage'){
        menuController.indexNoneSearchNavbar();
        mainView.hideToolbar();
    } else if (pageName === 'seller-shop') {
        $("#index-tool").html("").removeClass("toolbar");
        myApp.hideToolbar();
        App.hideSellerShop();
    } else if (pageName === 'detail') {
        App.detailBottomMenu();
    }
});
$$(document).on('pageInit', function (e) {
    // Get page data from event data
    var page = e.detail.page;
    if (page.name === 'index') {
        menuController.indexPage();
        /* $.post(Constant.ctx("/mulanweb/common/city/search"), {PageSize: 20, PageNumber: 1}, function (info) {
         var option = [];
         for (var i in info.DataList) {
         option[i] = ' <li onclick="changeCity(\'' + info.DataList[i].Id + '\',\'' + info.DataList[i].NameCn + '\')"><a href="#">' + info.DataList[i].NameCn + '</a></li>';
         if (i == 0 && option[0]) {
         $("#cityName").html(info.DataList[i].NameCn);
         $("#cityId").val(info.DataList[i].Id);
         }
         }
         $("#cityList").html(option.join(" "));
         });*/

    }else if(page.name === 'contentSearchTagPage'){
    }else if (page.name === 'keyWordSearchPage') {
        startKeyWordSearch();
    } else if (page.name === 'search') {
        totalPage = 1;
        loadSearchPage();
    } else if (page.name === 'seller-shop') {
        App.loadSellerShop();
    } else if (page.name === 'detail') {
        App.loadDetailPage();
    } else if (page.name === 'seller-shop') {
        App.loadSellerShop();
    } else if (page.name === 'reserve') {
        App.loadTicketReservePage();
    } else if (page.name === 'confirm_pay') {
        mainView.hideToolbar();
    }
})
var totalPage = 1;
//提示 已经没有内容了

//AddType 不等于null 表示刷新，否则表示无限加载
function addSearchResult(para, AddType) {
    if (para.PageNumber > totalPage) {
        if (alreadyAlert) {
            Constant.alertNotification("往下已没有更多内容了！");
            $$('.infinite-scroll-preloader').remove();
            alreadyAlert = false;
        }
        return false;
        App.hideLoading();
    }
    var url = Constant.ctx("/mulanweb/common/ticket/search");
    $.ajax({
        url: url,
        async: false,
        type: "post",
        dataType: "json",
        data: para,
        success: function (data) {
            if (data.ReturnCode == 1) {
                var template = $('#contentSearchDataList').html();
                var compiledTemplate = Template7.compile(template);
                var htmlStr = compiledTemplate(data);
                totalPage = data.TotalPage;
                if (AddType) {
                    $("#queryResultList").html(htmlStr);
                    currentPage = 1;
                } else {
                    $("#queryResultList").append(htmlStr);
                }
                if (data.TotalPage <= data.PageNumber) {
                    $$('.infinite-scroll-preloader').remove();
                }
                App.hideLoading();
            }
        }
    }, para, function (data) {
    });
}
var SearchDataPara = {};
function loadSearchPage() {
    var cityId = $("#search-cityId").val();
    var typeId = $("#search-typeId").val();
    var searchContent = $("#search-searchContent").val();
    SearchDataPara.PageSize = 10;
    SearchDataPara.PageNumber = 1;
    SearchDataPara.cityId = cityId;
    if (typeId == 0) {
        SearchDataPara.typeId = '';
    }
    SearchDataPara.searchContent = searchContent;
    //上拉无限加载
    var loading = false;
    var PageSize = 10;
    var PageNumber = 1;
    $$('.infinite-scroll').on('infinite', function () {
        if (loading) return;
        // 设置flag
        loading = true;
        currentPage = currentPage + 1;
        SearchDataPara.PageNumber = currentPage;
        addSearchResult(SearchDataPara);
        loading = false;
    });

    //下拉刷新  添加'refresh'监听器
    $$('.pull-to-refresh-content').on('refresh', function (e) {
        SearchDataPara.PageNumber = 1;
        SearchDataPara.PageSize = 10;
        if (!alreadyAlert) {
            alreadyAlert = true;
            var html = '<div class="infinite-scroll-preloader">' +
                '<div class="preloader" style="margin-left:48%"></div>' +
                '</div>';
            $$('.page-content').append(html);
        }
        $$('div[name=items]').remove();
        addSearchResult(SearchDataPara, "refresh");
        myApp.pullToRefreshDone();
    });
    addSearchResult(SearchDataPara, "refresh");
}

function changeOrder(orderBy, thisSpan) {
    //$(this).toggleClass("search-data-order-by");
    if (orderBy == 4) {
        wx.getLocation({
            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            success: function (res) {
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                var speed = res.speed; // 速度，以米/每秒计
                var accuracy = res.accuracy; // 位置精度
                SearchDataPara.longitude = longitude;
                SearchDataPara.latitude = latitude;
                if (SearchDataPara.latitude) {
                    changeOrder1(orderBy, thisSpan);
                    return;
                }
            },
        });
    } else {
        changeOrder1(orderBy, thisSpan);
    }
}
function changeOrder1(orderBy, thisSpan) {
    var label = $(".row .indexToolbar");
    if ($(thisSpan).hasClass("search-data-order-by")) {

    } else {
        for (var tt = 0; tt < label.length; tt++) {
            var src = $(label[tt]).children("img").attr("src");
            $(label[tt]).removeClass("search-data-order-by");
            $(label[tt]).children("img").attr("src", src.replace("-top-", "-bottom-"));
        }
        $(thisSpan).addClass("search-data-order-by");
        $(thisSpan).children("img").attr("src", src.replace("-bottom-", "-top-"));
    }
    var cityId = $("#search-cityId").val();
    var typeId = $("#search-typeId").val();
    SearchDataPara.PageSize = 10;
    SearchDataPara.PageNumber = 1;
    SearchDataPara.orderBy = orderBy;
    SearchDataPara.cityId = cityId;
    SearchDataPara.typeId = typeId;
    addSearchResult(SearchDataPara, "refresh");
}

function loadSearchHistory() {
    var url = "/mulanweb/common/ticket/searchUserHistory";
    var html = [];
    $.post(url,{},function(data){
        if(data.ReturnCode == 1){
            for(var i in data.DataList){
                html[i] = ' <li class="item-content searchHistory">' +
                        '<div class="item-media"><i></i></div>'+
                        '<div class="item-inner"><div class="item-title">'+data.DataList[i].Content+'</div></div></li>';
            }
            if(!data.TotalRow || data.TotalRow<=0){
                html[0]= ' <li class="item-content">' +
                    '<div class="item-inner"><div class="item-title">无历史记录</div></div></li>';
            }
        }else{
            html[0]= ' <li class="item-content">' +
                '<div class="item-inner"><div class="item-title">无历史记录</div></div></li>';
        }
        var t = html.join("")+'<li class="item-content" onclick="cleanSearchHistory()"><div style="margin:0 auto">清除历史记录</div></li>';
        $("#search_history").html(t);
        $(".searchHistory").on("click",function(){
            searchPara.searchKeyWord = $(this).text();
            $("#tool_input_searchKeyWord").val(searchPara.searchKeyWord);
            handler();
        });
    })
}

function startKeyWordSearch(){
    var url = Constant.ctx("/mulanweb/common/ticket/searchKeyWord");
    $.ajax({
        url: url,
        async: false,
        type: "post",
        dataType: "json",
        data: searchPara,
        success: function (data) {
            if (data.ReturnCode == 1) {
                var template = $('#contentSearchDataList').html();
                var compiledTemplate = Template7.compile(template);
                var htmlStr = compiledTemplate(data);
                $("#queryResultList").html(htmlStr);
                App.hideLoading();
            }
            App.hideLoading();
        }
    }, searchPara, function (data) {
    });
}

function cleanSearchHistory(){
    App.showLoading();
    var url = "/mulanweb/common/ticket/cleanSearchHistory";
    $.post(url,{},function(data){
        App.hideLoading();
        loadSearchHistory();
    })
    
}



